import { InteractionEvent, DisplayObject } from "pixi.js";
import { position } from "../../utils/pathFill";
import { AsPathFill } from "../../../assembly/AsPathFill";

/** 记录绘制的上一个点 */
let lastPoint = Promise.resolve(null) as Promise<position | null>;

/** 形成线性绘图的一个绑定 */
export const useDraw = (container: DisplayObject, stopPropagation = false) => {
    const data = { drawing: false, x: 0, y: 0, stopPropagation };

    const { pointerdown, pointermove, pointerup } = createEvents(
        data,
        container
    );
    const pointerout = (e: InteractionEvent) => {
        if (data.drawing) {
            pointerup(e);
        }
    };
    container.on("pointerdown", pointerdown);
    container.on("pointermove", pointermove);
    container.on("pointerup", pointerup);
    container.on("pointerout", pointerout);

    // 强制注入删除函数
    (data as any).stop = () => {
        container.off("pointerdown", pointerdown);
        container.off("pointermove", pointermove);
        container.off("pointerup", pointerup);
        container.off("pointerout", pointerout);
    };
    return data as typeof data & {
        stop: () => void;
    };
};
function createEvents(
    data: { drawing: boolean; x: number; y: number; stopPropagation: boolean },
    container: DisplayObject
) {
    /** 移动事件 */
    const pointermove = (e: InteractionEvent) => {
        if (data.stopPropagation) e.stopPropagation();
        if (data.drawing) {
            const { x, y } = e.data.getLocalPosition(container);
            // lastPoint 是必定有的
            lastPoint = lastPoint.then(async (res) => {
                const path = AsPathFill(res!, [x, y]);
                path.forEach(([x, y]) => {
                    container.emit("drawing", { x, y });
                });
                // 需要保存最后一个值
                const last = path.pop()! as position;
                return last;
            });
        }
    };

    const pointerdown = (e: InteractionEvent) => {
        if (data.stopPropagation) e.stopPropagation();
        data.drawing = true;
        const { x, y } = e.data.getLocalPosition(container);
        lastPoint = lastPoint.then(() => [x, y]);
        container.emit("drawStart", { x: Math.floor(x), y: Math.floor(y) });
    };
    const pointerup = (e: InteractionEvent) => {
        if (data.stopPropagation) e.stopPropagation();
        data.drawing = false;
        const { x, y } = e.data.getLocalPosition(container);

        container.emit("drawEnd", { x: Math.floor(x), y: Math.floor(y) });
        lastPoint = lastPoint.then(() => null);
        /** 抬笔时删除记录 */
    };
    return { pointerdown, pointermove, pointerup };
}
